package com.csyf.manager.channel.xiaojifu;

import com.alibaba.fastjson.JSONObject;
import com.csyf.manager.channel.base.PaymentVo;
import com.csyf.manager.channel.base.TrandeVo;
import com.csyf.manager.common.CommonConst;
import com.csyf.manager.entity.SysAgentChannel;
import com.csyf.manager.entity.SysPaymentChannel;
import com.csyf.manager.exception.ApiValidateException;
import com.csyf.manager.service.impl.RedisService;
import com.csyf.manager.utils.HttpHelper;
import com.csyf.manager.utils.NumberHelpler;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.TreeMap;

/**
 * 小机支付 支付宝
 */
@Slf4j
@Service
public class XiaojifuBiz {

    @Autowired
    private RedisService redisService;

    /**
     * 支付
     * @param vo
     * @param srcMerchId
     * @return
     * @throws ApiValidateException
     */
    public String dopay(TrandeVo vo, String srcMerchId) throws ApiValidateException {
        String channelStr = redisService.getSrcChannelInfo(vo.getMch_id(), srcMerchId);
        SysAgentChannel sysAgentChannel = new Gson().fromJson(channelStr, SysAgentChannel.class);

        Map<String, String> reqMap = new TreeMap<>();
        reqMap.put("uid", sysAgentChannel.getMerchantNo());
        reqMap.put("paytype", sysAgentChannel.getTermialId());
        reqMap.put("notify_url", sysAgentChannel.getNotifyUrl());
        reqMap.put("orderid", vo.getOut_trade_no());
        reqMap.put("orderuid", "eva_user");
        reqMap.put("money", NumberHelpler.cent2money(vo.getTotal_fee()).toString());

        // uid + istype + notify_url + orderid + orderuid +money+ token
        StringBuffer sbfStr = new StringBuffer();
        sbfStr.append(reqMap.get("uid")).append(reqMap.get("paytype")).append(reqMap.get("notify_url"))
                .append(reqMap.get("orderid")).append(reqMap.get("orderuid")).append(reqMap.get("money")).append(sysAgentChannel.getSignKey());
        log.info("[{}]小机支付交易签名字符串:{}", vo.getOut_trade_no(), sbfStr.toString());

        String signStr = DigestUtils.md5Hex(sbfStr.toString());
        reqMap.put("key", signStr);

        log.info("[{}]小机支付支付宝请求上游报文：{}", vo.getOut_trade_no(), reqMap.toString());
        String repStr = HttpHelper.doPostForm("http://xiaojifu.net/public_html/index.php/api/pay/index", reqMap, CommonConst.UTF8);
        log.info("[{}]小机支付支付宝上游响应报文：{}", vo.getOut_trade_no(), repStr);

        JSONObject jsonObject = JSONObject.parseObject(repStr);
        Integer code = jsonObject.getInteger("code");
        String data = jsonObject.getString("data");

        String qrcode = "";
        if (1 == code) {
            Map<String, String> dataMap = new Gson().fromJson(data, Map.class);
            qrcode = dataMap.get("payurl");
        } else {
            String msg = jsonObject.getString("msg");
            throw new ApiValidateException(code + "|" + msg);
        }
        return qrcode;
    }

    /**
     * 代付
     * @param vo
     * @param srcmch_id
     * @return
     * @throws ApiValidateException
     */
    public Map<String, String> dodfpay(PaymentVo vo, String srcmch_id) {
        String channelString = redisService.getPaymentChannelInfo(vo.getMch_id(), srcmch_id);
        SysPaymentChannel sysPaymentChannel = new Gson().fromJson(channelString, SysPaymentChannel.class);

        Map<String, String> reqMap = new TreeMap<>();
        reqMap.put("orderidext", vo.getOut_trade_no());
        reqMap.put("merchant_id", sysPaymentChannel.getMerchantNo());
        reqMap.put("money", NumberHelpler.cent2money(vo.getTrans_money()).toString());
        reqMap.put("bank_sheng", "广东省");
        reqMap.put("bank_shi", "东莞市");
        reqMap.put("bank_name", vo.getBank_name());
        reqMap.put("bank_zhihang", vo.getBankBranchname());
        reqMap.put("bank_people_name", vo.getAccount_name());
        reqMap.put("bank_card_no", vo.getBank_card());
        reqMap.put("notify_url", "http://localhost/eva/notify/testnotify");


        StringBuffer sbfStr = new StringBuffer();
        sbfStr.append(reqMap.get("merchant_id")).append(reqMap.get("money")).append(reqMap.get("bank_sheng"))
                .append(reqMap.get("bank_shi")).append(reqMap.get("bank_name")).append(reqMap.get("bank_zhihang"))
                .append(reqMap.get("bank_people_name")).append(reqMap.get("bank_card_no")).append(reqMap.get("notify_url"))
                .append(sysPaymentChannel.getSignKey());
        log.info("[{}]小机支付代付签名字符串:{}", vo.getOut_trade_no(), sbfStr.toString());

        String signStr = DigestUtils.md5Hex(sbfStr.toString());
        reqMap.put("key", signStr);

        log.info("[{}]小机支付支付宝代付请求上游报文：{}", vo.getOut_trade_no(), reqMap.toString());
        String rspStr = HttpHelper.doPostForm("http://xiaojifu.net/public_html/index.php/api/pay/tixian", reqMap, CommonConst.UTF8);
        log.info("[{}]小机支付支付宝代付上游响应报文：{}", vo.getOut_trade_no(), rspStr);

        Map map = new Gson().fromJson(rspStr, Map.class);
        return map;
    }

    /**
     * 查询代付
     * @param orderNo
     * @param mch_id
     * @param srcMchId
     * @return
     * @throws ApiValidateException
     */
    public Map<String, String> doqueryDf(String orderNo, String mch_id, String srcMchId) {
        String channelString = redisService.getPaymentChannelInfo(mch_id, srcMchId);
        SysPaymentChannel sysPaymentChannel = new Gson().fromJson(channelString, SysPaymentChannel.class);

        Map<String, String> reqMap = new TreeMap<>();
        reqMap.put("merchant_id", sysPaymentChannel.getMerchantNo());
        reqMap.put("orderid", orderNo);

        StringBuffer sbfStr = new StringBuffer();
        sbfStr.append(reqMap.get("merchant_id")).append(reqMap.get("orderid"))
                .append(sysPaymentChannel.getSignKey());

        String signStr = DigestUtils.md5Hex(sbfStr.toString());
        reqMap.put("key", signStr);

        log.info("[{}]小机支付支付宝代付查询请求上游报文：{}", orderNo, reqMap.toString());
        String rspStr = HttpHelper.doPostForm("http://xiaojifu.net/public_html/index.php/api/pay/tixianquery", reqMap, CommonConst.UTF8);
        log.info("[{}]小机支付支付宝代付查询上游响应报文：{}", orderNo, rspStr);
        Map map = new Gson().fromJson(rspStr, Map.class);
        return map;
    }




}
